package com.xqboss.apps.listener;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xqboss.apps.domain.hama.HamaUserOpen;
import com.xqboss.apps.enums.hama.HamaMixLogHireEnum;
import com.xqboss.apps.enums.mq.AppMqDelayEnum;
import com.xqboss.apps.enums.user.WalletLidouChangeTypeEnum;
import com.xqboss.apps.mapper.hama.HamaUserOpenMapper;
import com.xqboss.apps.service.hama.HamaUserMixService;
import com.xqboss.apps.util.mh.MoneyUtils;
import com.xqboss.common.core.mq.MqEnum;
import com.xqboss.common.core.mq.MqListener;
import com.xqboss.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 构建运动场空投力豆
 *
 * @author ljh
 * @date 2024/3/1
 */
@Slf4j
@Component
public class SportBuildListener extends MqListener {

    @Autowired
    private HamaUserOpenMapper mapper;

    @Autowired
    private HamaUserMixService hamaUserMixService;

    @Override
    public MqEnum getEnum() {
        return AppMqDelayEnum.SPORT_BUILD;
    }

    @Override
    public ConsumeResult solve(MessageView message) {
        String value = StandardCharsets.UTF_8.decode(message.getBody()).toString();
        List<Long> openIds= JSONArray.parseArray(value, Long.class);
        Date date = Date.from(LocalDateTime.now().truncatedTo(ChronoUnit.HOURS).atZone(ZoneId.systemDefault()).toInstant());//当前整点小时
        airdropBuild(openIds,date);
        return ConsumeResult.SUCCESS;
    }

    public void airdropBuild(List<Long> openIds,Date indexTime){
        log.info("-------- time:{}; hama-init-user-build:{}",indexTime, openIds);
        if (CollectionUtils.isNotEmpty(openIds)) {
            List<HamaUserOpen> userOpenList = mapper.selectList(new LambdaQueryWrapper<HamaUserOpen>().in(HamaUserOpen::getId,openIds));
            if(CollectionUtils.isEmpty(userOpenList)){
                return;
            }
            Map<Long,BigDecimal> helpOpenNum = new HashMap<>();//用户id,累计得空投力豆（多个运动场）
            for (HamaUserOpen open : userOpenList) {//具体业务
                int hireTime = (int) DateUtils.subtractMin(open.getHireTime(), indexTime);
                int time = 0;
                int isHire=1;
                if (hireTime > 0) {
                    time = (int) DateUtils.subtractMin(indexTime, open.getStartProductionTime());
                } else {
                    // 雇佣结束
                    time = (int) DateUtils.subtractMin(open.getHireTime(), open.getStartProductionTime());
                    isHire=0;
                }
                if (time > 0) {
                    // 根据 建设运动场蛙星人倍率 获取实际空投速率
                    BigDecimal openNum = MoneyUtils.multipleToScale6(open.getBasicSpeed(), DateUtils.minToHour(time));// 计算当前用户的收益（这段时间-分钟）
                    //是否已经达到挖矿上限
                    BigDecimal eggLayingNum = MoneyUtils.add(open.getEggLayingNum(), openNum);
                    if (eggLayingNum.compareTo(new BigDecimal(open.getToplimit())) != -1) {
                        //解散灵池
                        open.setEggLayingNum(new BigDecimal(open.getToplimit()));
                        open.setIsHire(HamaMixLogHireEnum.NO);
                        open.setStartProductionTime(indexTime);
                    } else {
                        //修改灵池
                        open.setEggLayingNum(MoneyUtils.add(open.getEggLayingNum(), openNum));
                        open.setStartProductionTime(indexTime);
                    }
                    if(isHire==0){
                        open.setEggLayingNum(new BigDecimal(open.getToplimit()));
                        open.setIsHire(HamaMixLogHireEnum.NO);
                        open.setStartProductionTime(indexTime);
                    }
                    mapper.updateById(open);
                    //增加开辟收益
                    BigDecimal bigDecimal = helpOpenNum.get(open.getUserId());
                    if (bigDecimal!=null && bigDecimal.compareTo(BigDecimal.ZERO) > 0) {
                        helpOpenNum.put(open.getUserId(),bigDecimal.add(openNum));
                    }else {
                        helpOpenNum.put(open.getUserId(),openNum);
                    }
                }else {
                    if(isHire==0){
                        open.setEggLayingNum(new BigDecimal(open.getToplimit()));
                        open.setIsHire(HamaMixLogHireEnum.NO);
                        open.setStartProductionTime(indexTime);
                        mapper.updateById(open);
                    }
                }
            }
            // 空投
            for (Map.Entry<Long, BigDecimal> entry : helpOpenNum.entrySet()) {
                Long userId = entry.getKey();
                BigDecimal openNum = entry.getValue();
                hamaUserMixService.addIncome(userId, 0L,openNum, WalletLidouChangeTypeEnum.SPORT_BUILD_INCOME);
            }
        }
    }

}